from rest_framework import serializers
from goods_info.models import GoodsCategoryModel

class GoodsCategorySerializer(serializers.ModelSerializer):
    """
        存货类别的序列化器，和反序列化
    """
    # read_only=True表示只是序列化的时候用
    children = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = GoodsCategoryModel
        fields = '__all__'

    # 函数的命名为：get_属性名
    def get_children(self, obj):  # obj当前的模型对象：GoodsCategoryModel对象
        if obj.children:
            # 加上.data: 使数据类型变成字典，原来是字典和列表的嵌套
            return GoodsCategorySerializer(obj.children, many=True).data
        else:
            return None
        pass